<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Branch Switch</title>
    </head>
    <body>
        <h1>Branch Switch</h1>
        <script>
            let activeEffect;
            function effect(fn) {
                activeEffect = fn;
                fn();
            }

            const data = {
                ok: true,
                text: 'hello world',
            };

            const bucket = new WeakMap();
            const obj = new Proxy(data, {
                get(target, key) {
                    track(target, key);
                    return target[key];
                },

                set(target, key, value) {
                    target[key] = value;
                    trigger(target, key);
                    return true;
                },
            });

            function track(target, key) {
                if (!activeEffect) return;

                let depsMap = bucket.get(target);
                if (!depsMap) {
                    bucket.set(target, (depsMap = new Map()));
                }

                let deps = depsMap.get(key);
                if (!deps) {
                    depsMap.set(key, (deps = new Set()));
                }

                deps.add(activeEffect);
            }

            function trigger(target, key) {
                const depsMap = bucket.get(target);
                if (!depsMap) return;

                const effects = depsMap.get(key);
                effects && effects.forEach((fn) => fn());
            }

            effect(function effectFn() {
                console.log('effect fn');
                document.body.innerText = obj.ok ? obj.text : 'not';
            });
        </script>
    </body>
</html>
